package org.icf.rest.service.security;

import java.io.IOException;
import java.io.Writer;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;

/**
 *
 */
public class JsonAuthenticationSuccessHandler  extends SimpleUrlAuthenticationSuccessHandler {

    public JsonAuthenticationSuccessHandler() {
    }

    /**
     * Constructor which sets the <tt>defaultTargetUrl</tt> property of the base
     * class.
     *
     * @param defaultTargetUrl the URL to which the user should be redirected on
     * successful authentication.
     */
    public JsonAuthenticationSuccessHandler(String defaultTargetUrl) {
        setDefaultTargetUrl(defaultTargetUrl);
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
            Authentication authentication) throws IOException, ServletException {
        String targetUrl = determineTargetUrl(request, response);

        if (response.isCommitted()) {
            logger.debug("Response has already been committed. Unable to redirect to " + targetUrl);
            return;
        }
        
        
        String targetPID = request.getParameter("targetPID");
        String targetKeycode = null;
        if (targetPID != null && !targetPID.trim().equals("")) {
        }

        HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(response);
        responseWrapper.setContentType("application/json");
        
        Writer out = responseWrapper.getWriter();
        if (targetKeycode == null) {
            out.write("{\"success\":true, \"newSessionId\": \"" + request.getSession(true).getId() + "\", \"targetUrl\": \"" + targetUrl + "\"}");
        } else {
            out.write("{\"success\":true, \"newSessionId\": \"" + request.getSession(true).getId() + "\", \"targetUrl\": \"" + targetUrl + "\"}");
        }
        out.close();

        clearAuthenticationAttributes(request);
    }
}
